package io.jft.doll.room.repository

import io.jft.doll.api.MessageApi
import io.jft.doll.api.apiProviderMock
import io.jft.doll.event.NotifyUrl
import io.jft.doll.room.entity.remote.MessageREntity
import com.g.base.help.postSimpleNotify
import com.g.base.room.repository.BaseRepository
import com.g.base.room.repository.MockDbLiveData
import com.g.base.room.repository.NetworkBoundResult

/**
 * Created by G on 2017/11/13 0013.
 */
class MessageRepository : BaseRepository() {
    companion object {
        val messageData by lazy { HashMap<String, MockDbLiveData<ArrayList<MessageREntity>>>() }
    }

    fun getMessageList(offset: Int, limit: Int,type : String) =
            NetworkBoundResult(
                    {
                        apiProviderMock.create(MessageApi::class.java)
                                .getMessageList(mapOf(Pair("offset", offset.toString()), Pair("limit", limit.toString()), Pair("type", type)))
                    },
                    {
                        messageData.getOrPut(type, { MockDbLiveData() })
                    },
                    {
                        true
                    },
                    {
                        messageData[type]!!.postValue(it)
                    }
            )

    fun getMessageCount() =
            NetworkBoundResult(
                    {
                        apiProviderMock.create(MessageApi::class.java)
                                .getMessageCount()
                    }
            )

    fun markMessageRead(id : String,type : String) =
            NetworkBoundResult(
                    {
                        apiProviderMock.create(MessageApi::class.java)
                                .markMessageRead(id)
                    },
                    onRemoteSucceed = {
                        run {
                            messageData[type]!!.value!!.forEach {
                                if (id == it.id) {
                                    it.read = false
                                    return@run
                                }
                            }
                        }
                        messageData[type]!!.postValue(messageData[type]!!.value!!)
                        postSimpleNotify(NotifyUrl.MessageCount)
                    }
            )

    fun delMessage(id : String,type : String) =
            NetworkBoundResult(
                    {
                        apiProviderMock.create(MessageApi::class.java)
                                .delMessage(id)
                    },
                    onRemoteSucceed = {
                        messageData[type]!!.postValue(messageData[type]!!.value!!.filter { id != it.id } as ArrayList<MessageREntity>?)
                        postSimpleNotify(NotifyUrl.MessageCount)
                    }
            )
}